package going.common;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

public class BaseMBean
{
	@SuppressWarnings("unchecked")
	protected <T extends Object> T findBean(Class<T> clazz, String beanName)
	{
		FacesContext context = FacesContext.getCurrentInstance();
		ELContext elcontext = context.getELContext();
		ExpressionFactory factory = context.getApplication().getExpressionFactory();
		ValueExpression exp = factory.createValueExpression(elcontext, "#{" + beanName + "}", clazz);
		Object obj = exp.getValue(elcontext);
		return (T) obj;
	}

	protected void mergeBean(Object bean, String beanName)
	{
		FacesContext context = FacesContext.getCurrentInstance();
		ELContext elcontext = context.getELContext();
		ExpressionFactory factory = context.getApplication().getExpressionFactory();
		ValueExpression exp = factory.createValueExpression(elcontext, "#{" + beanName + "}", bean.getClass());
		exp.setValue(elcontext, (bean == null) ? "" : bean);
	}
}
